﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Abp.Migration
{
    /// <summary>
    /// 提供注释语句
    /// </summary>
    public class SqlServerAnnotationProvider : IAnnotationProvider
    {
        public string GetColumnAnnotation(string schema ,string tableName, string columnName, string description)
        {
            
            return string.Format(@"if exists (select * from ::fn_listextendedproperty('MS_Description', 'schema', '{0}', 'table', '{1}', 'column', '{2}'))
BEGIN
    exec sys.sp_dropextendedproperty 'MS_Description', 'schema', '{0}', 'table', '{1}', 'column', '{2}'
END
exec sys.sp_addextendedproperty 'MS_Description', '{3}', 'schema', '{0}', 'table', '{1}', 'column', '{2}'
", GetSchema(schema), tableName, columnName, description);
        }

        public string GetTableAnnotation(string schema ,string tableName, string description)
        {
           
            return string.Format(@"if exists (select * from ::fn_listextendedproperty('MS_Description', 'schema', '{0}', 'table', '{1}', default, default))
BEGIN
    exec sys.sp_dropextendedproperty 'MS_Description', 'schema', '{0}', 'table', '{1}'
END
exec sys.sp_addextendedproperty 'MS_Description', '{2}', 'schema', '{0}', 'table', '{1}'
", GetSchema(schema), tableName, description);
        }

        private string WrapperWith(string orgin, string start = "[", string end = "]")
        {
            if (string.IsNullOrWhiteSpace(orgin))
                return string.Empty;
            if (!orgin.StartsWith(start))
                orgin = start + orgin;
            if (!orgin.EndsWith(end))
                orgin = orgin + end;
            return orgin;
        }

        private string GetTableName(string tableName, string schemaName)
        {
            string result = WrapperWith(schemaName);
            if (string.IsNullOrWhiteSpace(result))
                result = WrapperWith(tableName);
            else
                result += "." + WrapperWith(tableName);
            return result;

        }

        private string GetSchema(string schema)
        {
            if (string.IsNullOrWhiteSpace(schema))
                return "dbo";
            return schema;
        }
    }
}
